<template>
    <vp-dialog :span="4" ref="editDialogRef">
        <template #title>
            <vp-label zh="新增不正常事件清单" en="Add Abnormal List" v-if="type === 'add'"/>
            <vp-label zh="修改不正常事件清单" en="Edit Abnormal List" v-else/>
        </template>
        <div v-loading="loading">
            <AbnormalList :type="type" ref="abnormalListRef" />
        </div>
        <template #footer>
            <vp-btn-confirm @click="handleSave" />
        </template>
    </vp-dialog>
</template>
<script lang="ts">
import { defineComponent, nextTick, reactive, ref, toRefs } from 'vue';
import request from '/@/utils/request';
import AbnormalList from '../component/AbnormalList.vue';

export default defineComponent({
    name:'editAbnormalList',
    components: { AbnormalList},
    emits: ['formSubmited'],
    setup(props, context) {
        const state = reactive({
            type: 'add',
            loading: false,
            saveLoading: false,
            formData: {
            }
		});

        const editDialogRef = ref();
        const abnormalListRef = ref();

        const handleOpen = (param: { type: string; id: any;})=>{
            state.type = param.type;
            editDialogRef.value.handleOpen();
            nextTick(() => {
                if(param.type === 'edit'){
                    state.loading = true;
                    request.get(`/abnormal/list/${param.id}`).then((res)=>{
                        const data = {...res.data};
                        abnormalListRef.value.setData(data);
                        state.loading = false;
                    })
                } else {
                    abnormalListRef.value.setData({
                        ...state.formData,
                        ...param,
                    });
                }
			});
        }

        const handleSave = ()=>{
            if(state.loading){
                return;
            }
            state.saveLoading = true;
            abnormalListRef.value.getData().then((data: any)=>{
                request.post("/abnormal/list/"+state.type, {
                    ...data
                }).then(() => {
                    context.emit("formSubmited");
                    editDialogRef.value.handleClose();
                }).finally(()=>{
                    state.saveLoading = false;
                })
            }).catch(()=>{state.saveLoading = false;});
        }

        return {
            ...toRefs(state),
            handleSave,
            handleOpen,
            editDialogRef,
            abnormalListRef,
        }
    },
})
</script>